import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token';


export default {
    namespaced: true,
    state: {
        code: '',
        token: getToken(),
        userinfo: {}
    },
    actions: {
        //获取验证码
        async getCode({ commit }, phone) {
            //获取验证码的这个接口：把验证码返回，但是正常情况，后台把验证码发到用户手机上【省钱】
            let result = await reqGetCode(phone);
            if (result.code == 200) {
                commit("GETCODE", result.data);
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //注册
        async userRegister({ commit }, user) {
            let result = await reqUserRegister(user);
            if (result.code == 200) {
                console.log(result);
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //登录
        async userLogin({ commit }, user) {
            let result = await reqUserLogin(user);
            //服务器下发token,用户唯一标识符(uuid)
            //将来经常通过带token:找服务器要用户信息进行展示
            if (result.code == 200) {
                commit('USERLOGIN', result.data.token)
                setToken(result.data.token)
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        //获取用户信息
        async getUserInfo({ commit }) {
            let result = await reqUserInfo();
            if (result.code == 200) {
                // 提交用户信息
                commit('GETUSERINFO', result.data)
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }

        },
        //退出登录
        async userLogout({ commit }) {
            let result = await reqLogout();
            if (result.code == 200) {
                //清除数据，但state要在mutations操作
                commit('CLEAR')
                return 'ok'
            }
            else {
                return Promise.reject(new Error(result.message))
            }
        }

    },
    mutations: {
        GETCODE(state, code) {
            state.code = code;
        },
        USERLOGIN(state, token) {
            state.token = token
        },
        GETUSERINFO(state, userinfo) {
            state.userinfo = userinfo
        },
        CLEAR(state) {
            state.token = '';
            state.userinfo = {};
            removeToken();
        }
    },
    getters: {}

}